import React, { useState } from 'react';
import logo from '@/assets/logo.png';
import style from './index.module.scss';
import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { loginToken } from '@/store/actions/login';
import { useHistory } from 'react-router-dom';
import { setToken } from '@/utils/token';
export default function Login() {
  const history = useHistory();
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);
  const { token } = useSelector((state) => state.login);
  const onFinish = async (value) => {
    //走到这里说明表单验证都是没有问题的,类似element表单预校验通过
    // 发起请求获取到数据====>getToken是异步的
    try {
      setLoading(true);
      await dispatch(loginToken(value));
      // 页面跳转(成功后才跳转,怎样判断是否成功了====>不知道怎样判断,就使用监听状态)=====>保存token(刷新丢失问题)
      history.push('/home');
    } catch (error) {
      message.error('账号验证码错误');
      setLoading(false); //关闭loading效果
    }
  };
  return (
    <div className={style.root}>
      <Card className="login-container">
        <img src={logo} alt="" className="login-logo" />
        <Form
          size="large"
          validateTrigger={['onChange', 'onBlur']}
          initialValues={{
            mobile: '13111111111',
            code: '246810',
            remember: true,
          }}
          onFinish={onFinish}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3,9]\d{9}$/, message: '请输入正确的手机号' },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { pattern: /^\d{6}$/, message: '请输入6位验证码' },
            ]}
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="remember"
            wrapperCol={{ offset: 6, span: 18 }}
            valuePropName="checked"
            rules={[
              {
                validator(rule, value) {
                  if (value === true) return Promise.resolve();
                  else return Promise.reject(new Error('请阅读并同意'));
                },
              },
            ]}
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" block htmlType="submit" loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
